package com.edu.service.Impl;

import com.edu.dao.*;
import com.edu.data.*;
import com.edu.service.OrderService;
import com.edu.util.MyBatisUtil;
import org.apache.ibatis.session.SqlSession;
import org.springframework.stereotype.Service;

import java.sql.SQLException;

@Service
public class OrderServiceImpl implements OrderService {
    @Override
    public void payshoppingCart(ShoppingCart cart, User users, String address) throws SQLException {
        SqlSession sqlSession= MyBatisUtil.createSession();
        OrderMapper orderMapper=sqlSession.getMapper(OrderMapper.class);
        ProductMapper productMapper=sqlSession.getMapper(ProductMapper.class);
        OrderDetailMapper orderDetailMapper=sqlSession.getMapper(OrderDetailMapper.class);

        Order order = new Order();
        order.setEoUserId(users.getEuUserId());
        order.setEoUserName(users.getEuUserName());
        order.setEoUserAddress(address);
        order.setEoCost((double)cart.getTotalCost());
        order.setEoStatus(Order.STATUS_INITIAL);
        order.setEoType(Order.PAYTTYPE_CASH);
        orderMapper.insert(order);

        for (ShoppingCartItem item:cart.getItems()){
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setEoId(order.getEoId());
            orderDetail.setEodQuantity((int) item.getQuantity());
            orderDetail.setProduct(item.getProduct());
            orderDetail.setEodCost((double)item.getCost());
            orderDetail.setEpId(item.getProduct().getEpId());
            orderDetailMapper.insert(orderDetail);
            Product product = new Product();
            product.setEpStock((int)item.getQuantity());
            product.setEpId(item.getProduct().getEpId());
            productMapper.updateByPrimaryKeySelective(product);
        }
    }
}
